<?php


namespace dk\core;
use Exception;


class Dispatcher{

    /**
     * @var Router
     */
    protected $router;
    protected $actionPrefix = '';

    /**
     * @param Router $router
     */
    function __construct($router) {
        $this->router = $router;
    }
    /**
     * @return Router $router
     */
    public function getRouter(){
        return $this->router;
    }
    
    /**
     * @param string $cationtPrefix
     */
    public function setActionPrefix($actionPrefix) {
        $this->actionPrefix = $actionPrefix;
    }

    /**
     * @param $view
     * @return Action
     * @throws \Exception
     */
    function getAction(){
        // load action class
        $actions = explode('-', $this->router->getTask());
        $useRoot = false;
        if(count($actions) == 1){
            $useRoot = true;
            $actions[] = $this->router->getDefalutAction();
        }

        $lastAction = array_pop($actions);
        if($action = $this->router->getForceAction()){
            $actions[0] = 'all';
        }
        $action =  $this->actionPrefix . implode('\\', $actions) . '\\' . ucfirst($lastAction);
        if(class_exists($action)){
            return new $action();
        }

        // use root
        if($useRoot){
            $lastAction = array_pop($actions);
            $action =  $this->actionPrefix . ($actions ? (implode('\\', $actions) . '\\')  : '') . ucfirst($lastAction);
            if(class_exists($action)){
                return new $action();
            }
        }

        return null;
    }
}